package com.barradata.app0624.modules.bankcard

import android.Manifest
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.view.View
import com.barradata.BuildConfig
import com.barradata.R
import com.barradata.app0624.api.ApiService
import com.barradata.app0624.modules.camera.CameraActivity
import com.barradata.app0624.modules.camera.CameraCallbackEvent
import com.barradata.common.view.PlainTextPopupFragment
import com.barradata.app0624.modules.web.EventType
import com.barradata.app0624.modules.web.WebCallbackEvent
import com.barradata.common.base.BaseActivity
import com.barradata.common.rxbinding.clickV
import com.barradata.common.rxbus.RxBus
import com.barradata.common.utils.ToastUtils
import com.barradata.common.view.AlertDialogFragment
import com.example.hfiveandaplication.bean.DictionaryItemData
import com.example.hfiveandaplication.bean.IdentityData
import com.jakewharton.rxbinding3.widget.textChanges
import com.squareup.picasso.Picasso
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.rxkotlin.Observables
import kotlinx.android.synthetic.main.bank_auth_activity.*

/**
 * Author:    WuNan
 * Email:     wunan@barradata.com
 * Created:   2019/7/9 19:15
 **/
class BankAuthActivity : BaseActivity() {
    companion object {
        fun actionStart(context: Context) {
            val intent = Intent(context, BankAuthActivity::class.java)
            context.startActivity(intent)
        }

        private val REQUEST_PERMISSION = arrayOf(Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
    }

    private val rxPermissions = RxPermissions(this)
    private var dicItemData: ArrayList<DictionaryItemData>? = null
    private var selectedDicItem: DictionaryItemData? = null
    private var bankcardPhoto: IdentityData.ImageInfoBean? = null

    override fun getLayoutId() = R.layout.bank_auth_activity

    override fun initView() {
        setupActionBar(toolbar)
        fetchData()
        setupCameraButton()
        registerCameraCallback()
        registerPopupCallback()
        setupFormDataListener()
        setupNextButton()
    }

    override fun onBackPressed() {
        super.onBackPressed()
        RxBus.post(WebCallbackEvent(EventType.FROM_CANCEL))
    }

    private fun setupNextButton() {
        next_button.clickV().filter { checkFormData(true) }
                .flatMap {
                    ApiService.updateBankAuthInfo(bank_card_holder_et.text.toString(),
                            selectedDicItem!!.dictCode, selectedDicItem!!.dictValue,
                            bank_card_holder_et.text.toString())
                }
                .doOnSubscribe { showLoadingView() }
                .doFinally { dismissLoadingView() }
                .subscribe({
                    if (it.isRel) {
                        RxBus.post(WebCallbackEvent(EventType.FROM_BANK))
                        finish()
                    } else {
                        ToastUtils.showShort(it.message)

                    }
                }, {
                    it.printStackTrace()
                    ToastUtils.showShort(R.string.network_error)
                }).autoClean()
    }


    private fun setupFormDataListener() {
        Observables.combineLatest(bank_name_button.textChanges(),
                bank_card_number_et.textChanges(),
                bank_card_number_et2.textChanges(),
                bank_card_holder_et.textChanges()) { _, _, _, _ ->
            updateNextButton()
        }.subscribe().autoClean()
    }

    private fun registerPopupCallback() {
        bank_name_button.clickV().filter { checkDicData() }.subscribe {
            PlainTextPopupFragment(dicItemData!!.map { it.dictValue }).also {
                it.callbackAction = {
                    selectedDicItem = dicItemData!![it]
                    bank_name_button.setText(selectedDicItem?.dictValue)
                }
            }.show(this)
        }.autoClean()
    }

    private fun setupCameraButton() {
        bank_card_photo_layout.clickV().filter { checkPermission() }.subscribe {
            CameraActivity.actionStart(this, ApiService.UploadImageType.BANK_CARD)
        }.autoClean()
    }

    private fun registerCameraCallback() {
        RxBus.toObservable(CameraCallbackEvent::class.java).filter {
            it.photoType == ApiService.UploadImageType.BANK_CARD
        }.subscribe {
            uploadImage(it)
        }.autoClean()
    }

    private fun uploadImage(callbackEvent: CameraCallbackEvent) {
        ApiService.uploadImage(callbackEvent.photoType, callbackEvent.photoFile)
                .doOnSubscribe { showLoadingView() }
                .doFinally { dismissLoadingView() }
                .subscribe({
                    if (it.isRel) {
                        // 隐藏照片提示前景
                        camera_hint_group.visibility = View.GONE
                        // 关闭拍照事件
                        bank_card_photo_layout.isEnabled = false
                        // 加载照片
                        bankcardPhoto = it.data.imageInfo
                        Picasso.get().load(it.data.imageInfo.imageUrl).fit().into(bank_card_photo_iv)
                    } else {
                        ToastUtils.showShort(it.message)
                    }
                    updateNextButton()
                }, {
                    it.printStackTrace()
                    ToastUtils.showShort(R.string.network_error)
                }).autoClean()
    }

    private fun checkFormData(isShowToast: Boolean): Boolean {
        if (bankcardPhoto == null) {
            if (isShowToast) ToastUtils.showShort(R.string.please_upload_bank_card_pic_text)
            return false
        }
        if (bank_name_button.text.isEmpty()) {
            if (isShowToast) ToastUtils.showShort(R.string.bank_card_bind_bankname_hint)
            return false
        }
        if (bank_card_number_et.text!!.isEmpty()) {
            if (isShowToast) ToastUtils.showShort(R.string.personal_auth_bank_card_no_hint)
            return false
        }
        if (bank_card_number_et2.text!!.isEmpty()) {
            if (isShowToast) ToastUtils.showShort(R.string.personal_auth_bank_card_no_hint2)
            return false
        }
        if (bank_card_number_et.text.toString() != bank_card_number_et2.text.toString()) {
            if (isShowToast) ToastUtils.showShort(R.string.bank_card_number_error_hint)
            return false
        }
        if (bank_card_holder_et.text!!.isEmpty()) {
            if (isShowToast) ToastUtils.showShort(R.string.personal_auth_bank_card_username_hint)
            return false
        }
        return true
    }


    private fun updateNextButton() {
        if (checkFormData(false)) {
            next_button.alpha = 1f
        } else {
            next_button.alpha = 0.55f
        }
    }

    private fun fetchData() {
        ApiService.getDictionary(ApiService.DictionaryType.COMMON_BANKNAME)
                .doOnSubscribe { showLoadingView() }
                .doFinally { dismissLoadingView() }
                .subscribe({
                    if (it.isRel) {
                        dicItemData = it.data
                    }
                }, {
                    ToastUtils.showShort(R.string.network_error)
                    it.printStackTrace()
                }).autoClean()
    }

    private fun checkDicData(): Boolean {
        if (dicItemData.isNullOrEmpty()) {
            fetchData()
            return false
        }
        return true
    }


    private fun checkPermission(): Boolean {
        REQUEST_PERMISSION.iterator().forEach {
            if (!rxPermissions.isGranted(it)) {
                requestPermission()
                return false
            }
        }
        return true
    }

    private fun requestPermission() {
        rxPermissions.requestEachCombined(*REQUEST_PERMISSION).subscribe {
            if (it.granted) {
                return@subscribe
            }
            val singleButtonAction: (() -> Unit)?
            if (it.shouldShowRequestPermissionRationale) {
                singleButtonAction = { requestPermission() }
            } else {
                singleButtonAction = { go2Setting() }
            }
            ToastUtils.showShort(R.string.get_permission_failure_hint)
            AlertDialogFragment.create(singleButtonAction).setCancelAble(false)
                    .setTitle(getString(R.string.get_permission_failure_hint))
                    .show(this)
        }.autoClean()
    }

    private fun go2Setting() {
        val localIntent = Intent()
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        localIntent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
        localIntent.data = Uri.fromParts("package", BuildConfig.APPLICATION_ID, null)
        startActivity(localIntent)
    }
}